package cn.edu.abtu.utils;

import com.alibaba.druid.util.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class JwtUtils {

    //常量
    public static final long EXPIRE = 1000 * 60 * 60 * 24; //token的过期时间
    public static final String APP_SECRET = "12s2s3fdgdsdsa"; //加密所需的密钥

    //生成Token字符串
    public static String setJwtToken(String id, String nickname){
        String JwtToken = Jwts.builder()
                //JWT的Header部分
                .setHeaderParam("alg","HS256")
                .setHeaderParam("typ","JWT")

                //设置过期时间
                .setSubject("guli-user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))

                //需要存储在Token中的信息
                .claim("id",id)
                .claim("nickname",nickname)

                //根据密钥APP_SECRET和将编码方式(HS256)生成Token字符串
                .signWith(SignatureAlgorithm.HS256,APP_SECRET)
                .compact();
        return JwtToken;
    }

    //直接通过Token字符串验证token有效性
    public static boolean checkToken(String token){
        if (StringUtils.isEmpty(token)){
            return false;
        }
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //直接通过Header中获取token字符串验证有效性
    public static boolean checkToken(HttpServletRequest request){
        try {
            String token = request.getHeader("token");
            if (StringUtils.isEmpty(token)){
                return false;
            }
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //根据token获取用户id信息
    public static String getMemberIdByToken(HttpServletRequest request){
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            return "";
        }
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String) claims.get("id");
    }


}
